package com.zhanglijie.improve.atomic.four;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicReference;

import com.zhanglijie.base.sync.Lock.MyUnsafe;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/9/8 0008 0:00
 */
public class TestInnerUnsafeRefence {
    static MyCount myCount = new MyCount(0);
    private static AtomicReference<MyCount> atomicReference = new AtomicReference<>(myCount);

    static class MyCount{
         int money;//volatile是没有用的，解决方式 通过反射拿到这个字段 然后对这个字段cas操作即可

        @Override
        public String toString() {
            return "MyCount{" + "money=" + money + '}';
        }

        public int getMoney() {
            return money;
        }

        public MyCount(int money) {
            this.money = money;
        }

        public void setMoney(int money) {
            this.money = money;
        }
    }
    public static void main(String[] args) throws InterruptedException {
        TestInnerUnsafeRefence test = new TestInnerUnsafeRefence();
        CountDownLatch countDownLatch = new CountDownLatch(10000);
        for (int i = 0; i < 10000; i++) {
            int finalI = i;
            new Thread(()->{
                test.add(1);
                countDownLatch.countDown();
            }).start();

        }
        countDownLatch.await();
        System.out.println(atomicReference.get().getMoney());//应该是10000  但是有时候会出现9999之类不是1000的值

    }
    public void add(int i){
        MyCount myCount = atomicReference.get();
        myCount.setMoney(myCount.getMoney()+i);
    }
}
